<template>
  <div>
    <!-- excel复制数据粘贴到表格 -->
    <el-button @click="undo" size="mini" icon="el-icon-refresh-left" type="primary">撤销</el-button>
    <br />
    <!-- {{historyData}} -->
    <el-table
      ref="table"
      :data="tableData"
      border
      style="width: 100%"
      :cell-class-name="getCellIndex"
      @paste.native="pasteInfo($event)"
      @cell-click="cellClick"
    >
      <el-table-column prop="date" align="center" label="日期" width="180">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.date"
              placeholder="单行输入"
              clearable
              @click.native="handleNative"
            />
          </template>
      </el-table-column>
      <el-table-column prop="name" align="center" label="姓名" width="180">
        <template slot-scope="scope">
          <el-input v-model="scope.row.name" placeholder="单行输入" clearable />
        </template>
      </el-table-column>
      <el-table-column prop="address" align="center" label="地址">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.address"
            placeholder="单行输入"
            clearable
            @click.native="handleNative"
          />
        </template>
      </el-table-column>

      <el-table-column prop="jg" align="center" label="籍贯"></el-table-column>
      <el-table-column prop="gz" align="center" label="工作"></el-table-column>
      <el-table-column prop="xz" align="center" label="薪资"></el-table-column>

      <el-table-column width="200px" prop="age" align="center" label="年龄">
        <template slot-scope="scope">
          <el-input v-model.number="scope.row.age" placeholder="单行输入" clearable />
        </template>
      </el-table-column>
      <el-table-column prop="sex" align="center" label="性别">
        <template slot-scope="scope">
          <el-input v-model="scope.row.sex" placeholder="单行输入" clearable />
        </template>
      </el-table-column>
      <el-table-column prop="tel" align="center" label="电话">
        <template slot-scope="scope">
          <el-input v-model="scope.row.tel" placeholder="单行输入" clearable />
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
export default {
  name: "testDemo",
  data() {
    return {
      tableData: [
        {
          date: "2016-05-02",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
          jg: "北京",
          gz: "学生",
          xz: "0",
          age: 18,
          sex: "女",
          tel: "13112345678"
        },
        {
          date: "2016-05-04",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1517 弄",
          jg: "上海",
          gz: "销售",
          xz: "10000",
          age: 19,
          sex: "男",
          tel: "13112345678"
        },
        {
          date: "2016-05-01",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1519 弄",
          jg: "上海",
          gz: "行政",
          xz: "5000",
          age: 31,
          sex: "男",
          tel: "13112345678"
        },
        {
          date: "2016-05-03",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1516 弄",
          jg: "江苏",
          gz: "做生意",
          xz: "50000+",
          age: 48,
          sex: "男",
          tel: "13112345678"
        }
      ],
      rowIndex: undefined,
      columnIndex: undefined,
      historyData: [] // 历史数据
    };
  },
  methods: {
    /** 设置行、列索引 */
    getCellIndex: function({ row, column, rowIndex, columnIndex }) {
      row.index = rowIndex;
      column.index = columnIndex;
    },
    /** 点击单元格 */
    cellClick(row, column, cell, event) {
      // console.log(row, column, cell, event);
      this.rowIndex = row.index;
      this.columnIndex = column.index;
    },
    /** 复制粘贴 */
    pasteInfo(e) {
      try {
        e.preventDefault(); //阻止默认粘贴事件
        e.stopPropagation(); //阻止事件冒泡

        var data = null;
        var clipboardData = e.clipboardData || window.clipboardData; // IE
        if (!clipboardData) {
          //chrome
          clipboardData = e.originalEvent.clipboardData;
        }
        data = clipboardData.getData("Text"); //复制过来的内容
        //首先对源头进行解析
        var rowStrArray = data.split("\r\n"); //拆成多行
        console.log("拆分后数据", rowStrArray);
        let rows = [];
        for (var i = 0; i < rowStrArray.length - 1; i++) {
          var row = [];
          //   存在\t说明有存在多列
          var tdStrArray = rowStrArray[i].split("\t"); //按列拆分
          console.log("每行数据", tdStrArray);
          for (var j = 0; j < tdStrArray.length; j++) {
            row.push(tdStrArray[j]);
          }
          rows.push(row);
        }
        // rows得到的是一个二维数组，每一项对应一行的数据
        console.log(rows, "---------rows");
        const history = [];
        const columnHistory = []; // 列撤销历史数据
        let emptyObj = {
          //需要复制粘贴的key值列
          date: undefined,
          name: undefined,
          address: undefined,
          jg: undefined,
          gz: undefined,
          xz: undefined,
          age: undefined,
          sex: undefined,
          tel: undefined
        };
        for (var j = 0; j < rows.length; j++) {
          if (this.rowIndex + j > this.tableData.length - 1) {
            break;
          }
          let item = {};
          item = JSON.parse(JSON.stringify(this.tableData[this.rowIndex + j]));
          let num = 0;
          let numFlag = 0; //从哪一列开始粘贴：全部列都可以粘贴(即从第0列可以粘贴)
          for (var key in emptyObj) {
            // console.log(key,rows[j][num])
            if (!rows[j][num]) {
              break;
            }
            // console.log('numFlag--', numFlag, 'this.columnIndex--', this.columnIndex, 'num-', num);
            if (this.columnIndex <= numFlag) {
              // 针对不能修改的列字段做处理，可以复制粘贴的列才做赋值。根据需求加下面的if判断
              if (key !== "jg" && key !== "gz" && key !== "xz") {
                // 存储列撤销历史数据
                columnHistory.push({
                  index: this.rowIndex + j,
                  key,
                  oldValue: this.tableData[this.rowIndex + j][key],
                  newValue: item[key]
                });
                item[key] = rows[j][num];
              }
              num = num + 1;
            }
            numFlag = numFlag + 1;
          }
          console.log(item, "---item");
          history.push(columnHistory);
          this.$set(this.tableData, this.rowIndex + j, item);
        }
        this.historyData.push(history);
      } catch (err) {
        this.$message.error("请选择粘贴位置");
      }
    },
    // 撤销操作
    undo() {
      //   console.log(this.historyData);
      if (this.historyData.length > 0) {
        const history = this.historyData.pop();
        for (let i = 0; i < history.length; i++) {
          const columnHistory = history[i];
          for (let j = 0; j < columnHistory.length; j++) {
            const { index, key, oldValue } = columnHistory[j];
            this.$set(this.tableData[index], key, oldValue);
          }
        }
      }
    },
    // 单元格使用键盘上下切换
    handleNative() {
      const len = this.tableData.length;
      document.onkeydown = v => {
        //排除非input元素：移除键盘事件
        if (document.activeElement.nodeName.toLocaleLowerCase() !== "input") {
          return (document.onkeydown = null);
        }
        let curel = document.activeElement; //当前获得焦点的元素
        while (
          curel.nodeName.toLocaleLowerCase() !== "td" &&
          curel.nodeName.toLocaleLowerCase() !== "body"
        ) {
          curel = curel.parentElement;
        }
        if (curel.nodeName.toLocaleLowerCase() === "body") {
          return (document.onkeydown = null);
        }
        const curcellIndex = curel.cellIndex; // 当前元素列单元格索引
        // 当前所在table 的行的index : sectionRowIndex
        let index = curel.parentElement.sectionRowIndex;
        let curtbody = curel.parentElement; //当前tbody内容的整个表单
        console.log(curtbody);
        while (curtbody.nodeName.toLocaleLowerCase() !== "tbody") {
          curtbody = curtbody.parentElement;
        }

        const rowItem = i => curtbody.children[i].children[curcellIndex];
        // 13 enter| 40 下 |  38 上
        let flag = false;
        if (v.keyCode === 40 || v.keyCode === 38) {
          flag = true;
          this.oldInputNode = rowItem(index).getElementsByTagName("input")[0];
          this.oldRow = this.tableData[index];
        }

        if (v.keyCode === 40) {
          index += 1;
          if (index === len) {
            index = 0;
          }
        }
        if (v.keyCode === 38) {
          index -= 1;
          if (index < 0) {
            index = len - 1;
          }
        }
        if (flag) {
          const inputNode = rowItem(index).getElementsByTagName("input")[0];
          if (inputNode.dataset.disabled) {
            this.oldInputNode && this.oldInputNode.blur();
          } else {
            inputNode.focus();
          }
          this.$refs.table.setCurrentRow(this.tableData[index]);
        }
      };
    }
  }
};
</script>
